import asyncio
import time
import psutil
import time
import json

import falcon

from WebBackend.middleware.virtualWorldGate_Chuche import login_require


@falcon.before(login_require)
class SystemStatusAPI:
    async def on_get(self, req, resp):
        cpu = await asyncio.to_thread(psutil.cpu_percent, interval=0.5)
        ram = psutil.virtual_memory().percent
        swap = psutil.swap_memory().percent
        net_start = await asyncio.to_thread(psutil.net_io_counters)
        time.sleep(0.5)  # 等待 0.5 秒计算速率
        net_end = await  asyncio.to_thread(psutil.net_io_counters)
        net = {
            "total_output": net_end.bytes_sent,
            "total_input": net_end.bytes_recv,
            "upload_kbps": (net_end.bytes_sent - net_start.bytes_sent) / 1024,
            "download_kbps": (net_end.bytes_recv - net_start.bytes_recv) / 1024
        }
        system_stats = {
            "cpu": cpu,
            "ram": ram,
            'swap': swap,
            "network": net,
            "ts": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        resp.media = system_stats
        resp.status = falcon.HTTP_200
